package com.one.blocks.rbac.controller.valid;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Set;

/**
 * @author linfuxin Created on 2022-08-16 17:41:36
 */
@Slf4j
public class NoAllocatedDataValidatorForIntegerSet implements ConstraintValidator<NoAllocatedData, Set<Integer>> {

    @Autowired
    private ApplicationContext applicationContext;

    private AllocatedDataValidateManager<Integer> validateManager;

    @SuppressWarnings("unchecked")
    @Override
    public void initialize(NoAllocatedData constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        Class<? extends AllocatedDataValidateManager<Integer>> validManagerClass =
                (Class<? extends AllocatedDataValidateManager<Integer>>) constraintAnnotation.manager();
        validateManager = applicationContext.getBean(validManagerClass);
    }

    @Override
    public boolean isValid(Set<Integer> value, ConstraintValidatorContext context) {
        if (CollectionUtils.isEmpty(value)) {
            return true;
        }
        Integer[] existsDataKeys = validateManager.existsDataByKeys(value.toArray(new Integer[]{}));
        if (log.isDebugEnabled() && ArrayUtils.isNotEmpty(existsDataKeys)) {
            log.debug("关联数据:{}", existsDataKeys[0]);
        }
        return ArrayUtils.isEmpty(existsDataKeys);
//        if (ArrayUtils.isNotEmpty(existsDataKeys)) {
//            throw new AllocatedDataException(RbacResponseEnum.DELETE_ALLOCATED_DATA.getCode(), StringUtils.join(existsDataKeys, ","));
//        }
//        return true;
    }
}
